package 力扣刷题.探索初级算法.数组.买卖股票的最佳时机2;

import java.util.Scanner;

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length==1||prices.length==0) {
            return 0;
        }
        Integer buyPrice=null,sellPrice=null;
        int profit=0;
        if(prices[1]-prices[0]>0) {
            buyPrice=prices[0];
        }

        for(int i=1;i<prices.length-1;i++) {
            double leftSlope,rightSlope;
            leftSlope=prices[i]-prices[i-1];
            rightSlope=prices[i+1]-prices[i];
            if(leftSlope<=0&&rightSlope>=0) {
                buyPrice=prices[i];
            }
            else if(leftSlope>=0&&rightSlope<=0&&buyPrice!=null){
                sellPrice=prices[i];
                profit=profit+(sellPrice-buyPrice);
                buyPrice=null;
                sellPrice=null;
            }
        }
        if(buyPrice!=null) {
            profit=profit+prices[prices.length-1]-buyPrice;
        }
        return profit;
    }
    public static void main(String[] args) {

        int len;
        Scanner s=new Scanner(System.in);
        len=s.nextInt();
        int[] prices=new int[len];
        for (int i = 0; i < len; i++) {
            prices[i]=s.nextInt();
        }
        System.out.println(new Solution().maxProfit(prices));
    }
}
